<template>
  <div class="paper-info pad">
    <el-page-header class="page-header" @back="goBack" :content="title">
    </el-page-header>
    <div class="head">
      <span>问卷详情</span>
    </div>
    <el-tabs class="m-t-b" type="border-card">
      <el-tab-pane label="基础信息">
        <el-form v-loading="loading" :model="paper" :rules="rules" ref="paper">
          <el-form-item label="问卷名称" prop="name">
            <el-input v-model="paper.name" />
          </el-form-item>
          <el-form-item label="问卷编号" prop="id">
            <el-input v-model="paper.id" />
          </el-form-item>
          <el-form-item label="周期设置">
            <el-input-number v-model="paper.period" :min="0" :max="10"></el-input-number>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="saveBaseInfo('paper')">保存基本信息更新</el-button>
      </el-tab-pane>
      <el-tab-pane label="问题信息">
        <el-button type="primary" @click="showDialog = true"><i class="el-icon-plus"></i> 添加问题</el-button>
        <el-table stripe :data="labels">
          <el-table-column label="问题名称" prop="name"></el-table-column>
          <el-table-column label="A" prop="a"></el-table-column>
          <el-table-column label="B" prop="b"></el-table-column>
          <el-table-column label="C" prop="c"></el-table-column>
          <el-table-column label="D" prop="d"></el-table-column>
          <el-table-column label="是否启用">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enable"
                active-text="启用"
                inactive-text="禁用"
                @change="changeStatus($event, scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="添加问题" :visible.sync="showDialog">
      <el-form :model="label" ref="label" :rules="rules">
        <el-form-item label="问题描述" prop="labelQuestionId">
          <el-select v-model="label.labelQuestionId">
            <el-option v-for="item in questions" :key="item.labelQuestionId" :value="item.labelQuestionId" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="label.enable"
            active-text="启用"
            inactive-text="禁用"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitQuestion('label')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { notifySuccess, removeSame } from '../util'
import {
  getAllQuestion,
  getPaperQuestion,
  getOnePaper,
  setPaperQuestion,
  updateOnePaper
} from '../api'

export default {
  name: 'paper-info',
  props: ['id', 'name'],
  data () {
    let cycle = this.cycle
    return {
      letters: ['A', 'B', 'C', 'D'],
      showDialog: false,
      loading: true,
      title: '',
      period: cycle,
      label: {
        labelQuestionId: '',
        enable: true
      },
      labels: [],
      rules: {
        name: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ],
        id: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ],
        labelQuestionId: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ],
        questions: [
          { required: true, message: '该项不能为空!', trigger: 'blur' }
        ]
      },
      questions: [],
      paper: {
        name: '',
        id: '',
        period: 0,
        questions: []
      }
    }
  },
  methods: {
    goBack () {
      history.back()
    },
    saveBaseInfo (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          updateOnePaper({
            questionnaireId: this.id,
            name: this.paper.name,
            number: this.paper.id,
            cycle: this.paper.period
          })
          .then(res => {
            if (res.data.code === 1) {
              notifySuccess(this)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else {
          return false
        }
      })
    },
    submitQuestion (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          let oldList = this.labels.map(item => {
            return {
              labelQuestionId: item.labelQuestionId,
              enable: item.enable ? 1 : 0
            }
          })
          oldList.push({
            labelQuestionId: this.label.labelQuestionId,
            enable: this.label.enable ? 1 : 0
          })
          let newList = removeSame(oldList, 'labelQuestionId')
          setPaperQuestion({
            questionnaireId: this.id,
            questionList: newList
          })
          .then(res => {
            if (res.data.code === 1) {
              notifySuccess(this)
              this.showDialog = false
              this.fetchPaperQuestion(this.id)
            } else {
              this.$message.error(res.data.msg || '网络异常!')
            }
          })
          .catch(e => {
            this.$message.error('网络异常!')
          })
        } else {
          return false
        }
      })
    },
    saveQuestion (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          console.log(this.paper)
        } else {
          return false
        }
      })
    },
    fetchQuestions (type) {
      getAllQuestion(type)
      .then(res => {
        if (res.data.code === 1) {
          this.questions = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    fetchPaperQuestion (id) {
      getPaperQuestion(id)
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || []
          for (let i = 0; i < list.length; i ++) {
            list[i].enable = list[i].enable === 1 ? true : false
          }
          this.labels = list
          let tempList = []
          for (let i = 0; i < list.length; i ++) {
            tempList.push(list[i].labelQuestionId)
          }
          this.paper.questions = tempList
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
      })
      .catch(e => {
        this.$message.error('网络异常!')
      })
    },
    changeStatus (e, data) {
      this.$confirm(`确定${e ? '启用' : '禁用'}此问题?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setPaperQuestion({
          questionnaireId: this.id,
          questionList: this.labels.map(item => {
            return {
              labelQuestionId: item.labelQuestionId,
              enable: item.enable ? 1 : 0
            }
          })
        })
        .then(res => {
          if (res.data.code === 1) {
            notifySuccess(this)
            this.fetchPaperQuestion(this.id)
          } else {
            this.$message.error(res.data.msg || '网络异常!')
          }
        })
        .catch(e => {
          this.$message.error('网络异常!')
        })
      }).catch(() => {
        for (let i = 0; i < this.labels.length; i ++) {
          if (this.labels[i].labelQuestionId === data.labelQuestionId) {
            return this.labels[i].enable = !e
          }
        }
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    fetchOnePaper () {
      getOnePaper(this.id)
      .then(res => {
        if (res.data.code === 1) {
          let paper = res.data.data
          this.paper.name = paper.name
          this.paper.id = paper.number
          this.paper.period = paper.cycle
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        }
        this.loading = false
      })
      .catch(e => {
        this.$message.error('网络异常!')
        this.loading = false
      })
    }
  },
  created () {
    let path = this.$route.meta.path
    this.title = path[path.length - 1]
    this.fetchOnePaper()
    this.fetchPaperQuestion(this.id)
    this.fetchQuestions(2)
  }
}
</script>
<style lang="scss">
  .paper-info {}
</style>
